# -*- coding: UTF-8 -*- 
from xml.etree import ElementTree as ET
import urllib2
from deal_info_api import *

def deal_info_id(f_xml, deal, city):
    deal_id = deal.getiterator('id')
    if str(deal_id[0].text) == 'None':
	f_xml.close()
	os.system('rm %sxml/aibang_%s.xml' % (get_home_dir(), city))
	return 1
    for node in deal_id:
	f_xml.write(('\t' * 2 + '<id>%s</id>\n' % (node.text)).encode('utf-8'))
    return 0

def deal_city(tuan, city, city_id):
    (f_id, d_id, orig) = judge_begin(tuan, city)
    
    f_url = urllib2.urlopen('http://tuan.aibang.com/api/v1/%s/deals' % (city_id))

    root_url = ET.fromstring(f_url.read())

    f_xml = open('%sxml/%s_%s.xml' % (get_home_dir(), tuan, city), 'w')

    f_xml.write('<deals>\n')

    deals = root_url.getiterator('deal')
    for deal in deals:
	if judge(f_id, d_id, deal, 'id'):
	    continue

	f_xml.write('\t' + '<deal>\n')
	deal_info_source(f_xml, 'aibang', '爱帮网'.decode('utf-8'), 'http://tuan.aibang.com/', 'http://tuan.aibang.com/t/722313')
    	f_xml.write('\t' * 2 + '<city>%s</city>\n' % city)

	if deal_info_id(f_xml, deal, city):
	    return
	deal_info_add(f_xml, deal, 'title', 'name', 2)
	deal_info_cats(f_xml, deal, 'title')
	deal_info_vendor_1(f_xml, deal)
	deal_info_add(f_xml, deal, 'start_date', 'start_time', 2)
	deal_info_add(f_xml, deal, 'end_date', 'end_time', 2)
	deal_info_add(f_xml, deal, 'value', 'o_price', 2)
	deal_info_add(f_xml, deal, 'price', 'c_price', 2)
	deal_info_discount_and_save_money(f_xml, deal, 'price', 'value')
	deal_info_img(f_xml, deal, 'large_image_url')
	deal_info_add(f_xml, deal, 'deal_url', 'url', 2)

	f_xml.write('\t' + '</deal>\n')

    f_xml.write(orig[8 : ])

    f_xml.close()
    f_id.close()

    judge_end(tuan, city)


city_list = open('%slist/citylist' % (get_home_dir()), 'r')
cities = eval(city_list.read())

f_city = urllib2.urlopen('http://tuan.aibang.com/api/v1/divisions')
root_city = ET.fromstring(f_city.read())
city_id = root_city.getiterator('id')
city_name = root_city.getiterator('city')

for i in range(len(city_name)):
    try:
	deal_city('aibang', cities[city_name[i].text.encode('utf-8')], city_id[i].text)
    except KeyError:
	os.system(('date >> %serror.log && echo "%s KeyError: %s\n" >> %serror.log' % (get_home_dir(), 'aibang', city_name[i].text)).encode('utf-8'), get_home_dir())


